import React, { memo,useRef,useState } from 'react'
import { DemoWrapper } from './style'

const Demo = memo(() => {
  const [list,setList] = useState(() => ["a","b","c","d","e","f","g","h",])
  const [currentIndex,setCurrentIndex] = useState(0)
  const listRef = useRef()
  function preClick(){
    console.log('pre')
  }
  function nextClick(){
    let newIndex = currentIndex+1
    if(newIndex < 0) newIndex = list.length - 1
    if(newIndex > list.length - 1) newIndex = 0
    setCurrentIndex(newIndex)
    let currentItemEl = listRef.current.children[newIndex]
    const scrollWidth = listRef.current.scrollWidth
    const clientWidth = listRef.current.clientWidth
    const itemLeft = currentItemEl.offsetLeft
    const itemWidth = currentItemEl.clientWidth
    let distance = itemLeft + itemWidth * 0.5 - clientWidth * 0.5
  
    if(distance < 0) distance = 0
    if(distance > scrollWidth - clientWidth) distance = scrollWidth - clientWidth
    
    listRef.current.style.transform = `translate(${-distance}px)`

  


    console.log('next',"scrollWidth:",scrollWidth,"clientWidth:",clientWidth,"currentItemEl:",currentItemEl,"itemLeft:",itemLeft)

  }
  return (
    <DemoWrapper color="#666">
      <span onClick={preClick}>pre </span>
      <span onClick={nextClick}> next</span>
     <div className='list'>
      <div className='item' ref={listRef} >
        {
          list.map((item,index) => {
            return <div key={index}>{item}</div>
          })
        }
      </div>
     </div>
    </DemoWrapper>
  )
})

export default Demo